<?php


namespace App\controllers\v1;


use App\controllers\Base;
use App\models\CustomerSession;
use Consts\RedisKey;
use Helper\Output;
use Helper\Mysql;
use Helper\Redis;


class Select extends Base
{

    /**
     * 选择问题
     * @param $server
     * @param $fd
     * @param $param
     * @return bool
     */
    public function submitProblem($request, $response){

        try {
            $param = $request->post;
            //寻找当前问题的客服
            $list = Redis::getInstance()->sMembers(RedisKey::platform_online_service($param['p'] ,$param['problem_id']));
            if(!$list){
                return  Output::json(1013);
            }
            $admin_user =  Redis::getInstance()->hGet(RedisKey::ADMIN_SERVICE_INFO_LIST,'id:'.$list[0]);
            $admin_user = json_decode($admin_user,true);
            unset($admin_user['password']);
            unset($admin_user['username']);
            return    Output::json(200,$admin_user);

        }catch (\Exception $e){

            return Output::json(1001,$e->getMessage());
        }


    }


    /**
     * 选择客服
     * @param $server
     * @param $fd
     * @param $param
     * @return bool
     */
    public function selectKF($request, $response){
        $param = $request->post;
        $auid = $param['auid'];
        $uid  = $param['uid'];
        if(!$auid){
            return Output::json(1018);
        }
        if(!$uid){
            return Output::json(1019);
        }

        //检测有没有未关闭的会话
        $sess = Mysql::getInstance()
            ->where('auid',$auid)
            ->where('uid',$uid)
            ->where('end_at',0)
            ->getOne('customer_session');

        if($sess){
            return   Output::json(200,['sessid'=> $sess['id'] ]);
        }

        //该客服正在接待会话数量
        $num = Redis::getInstance()->hLen(RedisKey::online_customer_list($auid));
        $admin_user =  Redis::getInstance()->hGet(RedisKey::ADMIN_SERVICE_INFO_LIST,'id:'.$auid);
        if(!$admin_user){
            return  Output::json(1025);
        }
        $admin_user = json_decode($admin_user,true);
        if($num >= $admin_user['max_service_num'] ){

            if( !Redis::getInstance()->hget(RedisKey::CUSTOMER_BIND_SERVICE,'uid:'.$uid)){
                //加入排队--需要判断不要重复排队
                Redis::getInstance()->zAdd(RedisKey::service_queue_list($auid),time(),$uid);
                //绑定用户和客服的排队关系
                Redis::getInstance()->hSet(RedisKey::CUSTOMER_BIND_SERVICE,'uid:'.$uid,$auid);
            }

            $top = Redis::getInstance()->zRank(RedisKey::service_queue_list($auid) ,$uid );
            return Output::json(1014,['queue_num'=> $top+1 ]);
        }
        //创建会话ID
        $sessid =  CustomerSession::createSession( $auid ,$uid);
        if($sessid){

            return Output::json(200,['sessid'=> $sessid ]);
        }else{

            return Output::json(1015);
        }

    }




}